package cn.sciento.boot.data.change.parse;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import cn.sciento.boot.data.change.dto.MybatisInvocation;
import cn.sciento.boot.data.change.helper.KeyGeneratorHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InsertDataParser extends AbstractDataParser {
  private static final Logger logger = LoggerFactory.getLogger(InsertDataParser.class);
  
  private static final String REWRITING_PARAM_KEY = "collection";
  
  public List<Map<String, Object>> parseBefore(MybatisInvocation mybatisInvocation) throws Throwable {
    List<Map<String, Object>> beforeData = new ArrayList<>();
    return beforeData;
  }
  
  public List<Map<String, Object>> parseAfter(MybatisInvocation mybatisInvocation, List<Map<String, Object>> beforeData) throws Throwable {
    beforeData = buildBeforeData(mybatisInvocation);
    if (CollectionUtils.isEmpty(beforeData)) {
      logger.info("there is nothing of before Data");
      return beforeData;
    } 
    return queryAfterAffectedData(mybatisInvocation, beforeData);
  }
  
  private List<Map<String, Object>> buildBeforeData(MybatisInvocation mybatisInvocation) {
    List<Map<String, Object>> beforeData = new ArrayList<>();
    String keyProperty = mybatisInvocation.getTable().getKeyProperties()[0];
    String keyColumn = mybatisInvocation.getTable().getKeyColumns()[0];
    String keyPropertyForGenerator = keyProperty;
    String[] keyPropertiesForGenerator = mybatisInvocation.getMappedStatement().getKeyProperties();
    if (keyPropertiesForGenerator != null && keyPropertiesForGenerator.length != 0)
      keyPropertyForGenerator = keyPropertiesForGenerator[0]; 
    List<Object> keyValuesFromParameter = KeyGeneratorHelper.findKeyValuesFromParameter(keyPropertyForGenerator, mybatisInvocation
        .getParameter());
    if (CollectionUtils.isEmpty(keyValuesFromParameter))
      keyValuesFromParameter = KeyGeneratorHelper.findKeyValuesFromSql(mybatisInvocation); 
    if (CollectionUtils.isNotEmpty(keyValuesFromParameter))
      for (Object keyValue : keyValuesFromParameter) {
        Map<String, Object> data = new HashMap<>(1);
        data.put(keyColumn, keyValue);
        beforeData.add(data);
      }  
    return beforeData;
  }
}
